package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.Assert;
import com.woniu.enumeration.BusinessCode;
import com.woniu.enumeration.UserStatusType;
import com.woniu.pojo.User;
import com.woniu.service.UserService;
import com.woniu.mapper.UserMapper;
import com.woniu.vo.LoginRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
* @author YangChuanDong
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2024-12-10 16:15:47
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录验证
     * 步骤：
     *  1.判断用户名是否存在
     *      否：返回用户名不存在信息
     *  2.判断密码是否正确，判断加密后面膜
     *      否：返回密码错误信息
     *  3.判断账号状态
     *      否：返回账号不可用状态信息
     *  4.登录成功，返回user 对象
     * @params 封装了前端请求的 用户名和密码
     *
     */
    public ResponseEntity login(LoginRequest params) {
        // 获取验证嘛 key
        String key = params.getKey();
        log.info("key：" + key);
        // 得到redis验证码
        String code = (String) stringRedisTemplate.opsForValue().get(key);
        // 判断是否过期
        Assert.error(code == null, BusinessCode.INVALID_VERIFICATION);
//        if (code == null) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("验证码过期");
//        }

        // 判断验证码是否正确
        Assert.error(!code.equalsIgnoreCase(params.getCode()), BusinessCode.VERIFICATION_ERROR);
//        if (!code.equalsIgnoreCase(params.getCode())) {
//            return ResponseEntity.badRequest().body("验证码错误");
//        }

        // 验证成功，删除redis验证码
        stringRedisTemplate.delete(key);


        // 查询账户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getAccount, params.getAccount());
        User user = userMapper.selectOne(wrapper);
        // 1.判断用户名是否存在
//        Assert.error(user == null, BusinessCode.USER_NOT_EXIST);
        if (user == null) {
            return ResponseEntity.badRequest().body(BusinessCode.USER_NOT_EXIST);
        }
        /**
         *  2.判断密码是否正确，判断加密后面膜
         *      BCryptPasswordEncoder是一种加密方式
         *      数据库查出密码是加密后的密码，前端传过来的密码是明文，需要和数据库密码进行比较
         *      返回值是boolean类型，true表示密码正确，false表示密码不正确
         */
        boolean matches = new BCryptPasswordEncoder()
                .matches(params.getPassword(), user.getPassword());
        Assert.error(!matches, BusinessCode.PASSWORD_ERROR);

//        if (!matches) {
//            return ResponseEntity.badRequest().body("密码错误");
//        }

        // 3.判断账号状态
        Assert.error(user.getState() != UserStatusType.ACTIVE.getKey(), BusinessCode.USER_FROZEN_ERROR);
//        if (user.getState() != UserStatusType.ACTIVE.getKey()) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("账号不可用");
//        }

        // 4.登录成功，返回user 对象
        return ResponseEntity.ok(user);
    }

    /**
     * 通过手机号查询用户是否存在
     * */
    @Override
    public User findByTelephone(String telephone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getMobile, telephone);
        User user = userMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public boolean isEmailExist(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getEmail, email);

        return userMapper.selectOne(wrapper) != null;
    }

    /**
     * 判断账户名是否存在
     * */
    @Override
    public boolean isAccountExist(String account) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getAccount, account);
        User user = userMapper.selectOne(wrapper);
        return user != null;
    }

    @Override
    public boolean isMobileExist(String mobile) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getMobile, mobile);

        return userMapper.selectOne(wrapper) != null;
    }

    /**
     * 注册用户，返回用户对象
     * */
    @Override
    public User register(User user) {
        // 对密码进行加密处理
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        // 设置用户状态
        user.setState(UserStatusType.ACTIVE.getKey());

        // 更新数据库
        userMapper.insert(user);
        return user;
    }


}




